<script setup lang="ts">
import Header from './components/Header.vue'
import IncomeExpenses from './components/IncomeExpenses.vue'
import Balance from './components/Balance.vue'
import TransactionList from './components/TransactionList.vue'
import AddTransaction from './components/AddTransaction.vue'
import type { Transaction } from './types'
import { computed, onMounted, ref, watch } from 'vue'
import { loadTransactionsFromLocalStorage, saveTransactionsToLocalStorage } from './utils'

const transactionArr = ref<Transaction[]>([])

onMounted(() => transactionArr.value.push(...loadTransactionsFromLocalStorage()))

watch(
  () => transactionArr.value.length,
  () => {
    console.log('watch到transactionArr变化')
    saveTransactionsToLocalStorage(transactionArr.value)
  }
)

const income = computed((): string => {
  return transactionArr.value
    .filter((item) => item.amount > 0)
    .reduce((acc, item) => (acc += item.amount), 0)
    .toFixed(2)
})

const expenses = computed((): string => {
  return (
    transactionArr.value
      .filter((item) => item.amount < 0)
      .reduce((acc, item) => (acc += item.amount), 0) * -1
  ).toFixed(2)
})

const total = computed((): string => {
  return transactionArr.value.reduce((acc, item) => (acc += item.amount), 0).toFixed(2)
})

// 处理添加的数据
function handleTransactionSubmit(value: Transaction) {
  console.log('添加数据:', value.title)

  transactionArr.value.push(value)
  // 使用watch来解决
  // saveTransactionsToLocalStorage(transactionArr.value)
}

// 删除数据
function handleTransactionDelete(id: number) {
  console.log(`删除id = ${id}的数据`)
  transactionArr.value = transactionArr.value.filter((item) => item.id != id)
  // 使用watch来解决
  // saveTransactionsToLocalStorage(transactionArr.value)
}
</script>

<template>
  <div class="container">
    <div class="expanse-tracker__container">
      <Header />
      <Balance :balance="total" />
      <IncomeExpenses :income="income" :expenses />
      <TransactionList :transactionArr @transaction-deleted="handleTransactionDelete" />
      <AddTransaction @transaction-submitted="handleTransactionSubmit" />
    </div>
  </div>
</template>

<style lang="scss">
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f7f7f7;

  .expanse-tracker__container {
    padding: 20px;
    min-width: 550px;
    height: 100%;
    /* background-color: red; */
  }
}
</style>
